package SwingView.Lecture;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;

import JDBC.InstructorLectureActivities;
import SwingController.CmsPresenter;
import SwingModel.CmsInstructor;
import SwingModel.CmsLecture;
import SwingModel.CmsUser;
import SwingView.CmsMainView;

public class ALLecturePost implements ActionListener{

	@Override
	public void actionPerformed(ActionEvent e) {
		
		//get components
		final CmsMainView mainView = CmsPresenter.mainView;
		final CmsInstructor instructor = (CmsInstructor) CmsPresenter.user;
		final LectureUploadPanel lup = mainView.getContentPanel().getLectureInstructorPage().getLectureUploadPanel();
		
		//get parameter to instantiate new lecture
		File selectedFile = lup.getSelectedFile();
		Date avaiDate = lup.getSelectedAvaiDate();
		Date expDate = lup.getSelectedExpDate();
		
		//VALIDATE USER INPUT AND PERFORM POSTING
		if( lup.validateAllInput()) {
			try{
				//Copy the file from selected directory to the local directory -- the lecture folder
				Files.copy(Paths.get(selectedFile.getPath()),
								Paths.get("./lecture/" + selectedFile.getName()), 
								StandardCopyOption.REPLACE_EXISTING);
				//get the file from lecture folder
				File file = new File("./lecture/" + selectedFile.getName());
				
				//instantiate new lecture
				CmsLecture lecture = new CmsLecture(0,
										instructor.getSelectedCourse().getCourseID(),
										file,
										avaiDate,
										expDate);
				
				//instructor post lecture:
				InstructorLectureActivities.postLecture(instructor.getSelectedCourse().getCourseID(), lecture);
				
				lup.clearAllInput();
				//display lecture instructor Page
				mainView.displayLectureInstructorPage(InstructorLectureActivities.getListOfLecture(instructor.getUsername(), instructor.getSelectedCourse().getCourseID()));
				
			} catch (IOException e1) {
				System.err.println("Copy file failed");
				e1.printStackTrace();
			}
		}
	}

}
